<template>
  <el-row :gutter="20">
    <!-- 分类树 -->
    <el-col :lg="4" :xs="24">
      <el-card shadow="hover" class="rd-8">
        <el-input
          v-model="subjectName"
          placeholder="请输入课程分类名称"
          prefix-icon="Search"
          clearable
        />
        <el-tree
          class="mt-2"
          ref="subjectTreeRef"
          node-key="id"
          :data="subjectOptions"
          :props="{ label: 'title', children: 'children' }"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          highlight-current
          default-expand-all
          @node-click="handleNodeClick"
        />
      </el-card>
    </el-col>
    <el-col :lg="20" :xs="24">
      <!-- 查询条件 -->
      <el-card shadow="hover" class="rd-8">
        <el-form inline :model="queryParams">
          <el-form-item label="课程标题">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入课程标题"
              clearable
              class="query_width"
            />
          </el-form-item>
          <el-form-item label="讲师">
            <el-select
              v-model="queryParams.teacherId"
              clearable
              placeholder="请选择讲师"
              class="query_width"
            >
              <el-option
                :label="item.name"
                :value="item.teacherId"
                v-for="item in teacherOptions"
                :key="item.teacherId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" class="date_width">
            <el-date-picker
              value-format="YYYY-MM-DD"
              clearable
              v-model="dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="getHasCourse()">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- table -->
      <el-card shadow="hover" class="mt-10 rd-8">
        <template #header>
          <el-button type="primary" icon="Plus" plain @click="handleAdd()">
            新增
          </el-button>
          <el-button
            type="danger"
            icon="Delete"
            plain
            :disabled="selectedCourses.ids.length === 0"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </template>
        <el-table
          :data="tableData"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="title"
            label="标题"
            width="200"
            align="center"
          />
          <el-table-column
            label="课程封面"
            prop="coverUrl"
            width="180"
            align="center"
          >
            <template #default="{ row }">
              <img :src="row.coverUrl" alt="课程封面" width="150" />
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price" width="140" align="center">
            <template #default="{ row }">
              <el-tag type="danger">
                {{ row.price == 0 ? '免费' : `￥${row.price}` }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="lessonNum"
            label="课时数"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.lessonNum }}课时</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="buyCount"
            label="购买学员"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.buyCount }}人</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="viewCount"
            label="访问数量"
            width="140"
            align="center"
          />
          <el-table-column
            prop="status"
            label="发布状态"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              <el-tag>{{ row.status == '0' ? '未发布' : '已发布' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            align="center"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
            align="center"
          >
            <template #default="{ row }">
              <el-tooltip content="修改课程信息" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  text
                  icon="Edit"
                  @click="handleEditCourse(row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改章节信息" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  text
                  icon="EditPen"
                  @click="handleEditChapter(row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  text
                  icon="Delete"
                  @click="handleDelete(row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="mt-10"
          v-show="total > 0"
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 8, 13, 15]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="getHasCourse"
          @size-change="getHasCourse"
        />
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { reqDeleteCourse, reqPageCourse } from '@/api/course'
import { Course, CourseQuery } from '@/api/course/type'
import { reqSubjectTree } from '@/api/subject'
import { Subject } from '@/api/subject/type'
import { reqTeacherList } from '@/api/teacher'
import { TeacherVo } from '@/api/teacher/type'
import { addDateRange } from '@/utils/util'
import type { DateModelType } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
let queryParams = ref<CourseQuery>({
  title: undefined,
  subjectId: undefined,
  teacherId: undefined,
})
let dateRange = ref<[DateModelType, DateModelType]>(['', ''])
let tableData = ref<Course[]>([])
let pageSize = ref<number>(8)
let pageNum = ref<number>(1)
let total = ref<number>(0)
let selectedCourses = reactive<{ ids: string[]; titles: string[] }>({
  ids: [],
  titles: [],
})

/* 重置查询 */
const resetQuery = async () => {
  dateRange.value = ['', '']
  queryParams.value = {
    title: undefined,
    subjectId: undefined,
    teacherId: undefined,
  }
  await getHasCourse()
}

const handleSelectionChange = (val: Array<Course>) => {
  selectedCourses.ids = val.map((item) => item.courseId) as Array<string>
  selectedCourses.titles = val.map((item) => item.title)
}

/** 删除按钮操作 */
const handleDelete = async (row?: Course) => {
  const courseIds = row?.courseId || selectedCourses.ids
  const titles = row?.title || selectedCourses.titles
  try {
    await ElMessageBox.confirm(
      '是否确认删除课程标题为"' + titles + '"的数据项？',
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    await reqDeleteCourse(courseIds)
    ElMessage.success('删除成功')
    await getHasCourse()
  } catch (error) {
    return
  }
}

/* 新增按钮 */
const handleAdd = () => {
  router.push(`/course/save`)
}
/* 修改按钮 */
const handleEditCourse = (row: Course) => {
  router.push(`/course/edit/${row.courseId}`)
}
const handleEditChapter = (row: Course) => {
  router.push(`/course/chapter/${row.courseId}`)
}
/** 查询用户列表 */
const getHasCourse = async (pager = 1) => {
  pageNum.value = pager
  let result = await reqPageCourse(
    pageNum.value,
    pageSize.value,
    addDateRange(queryParams.value, dateRange.value),
  )
  tableData.value = result.rows
  total.value = result.total
  // console.log(result.rows)
}

/* teacherList */
let teacherOptions = ref<TeacherVo[]>([])
const getTeacherList = async () => {
  let { data } = await reqTeacherList()
  teacherOptions.value = data
}

/* 分类树 */
let subjectName = ref<string>('')
let subjectOptions = ref<Subject[]>([])
const filterNode = (
  value: string,
  data: {
    [title: string]: string
  },
) => {
  if (!value) return true
  return data.title.includes(value)
}
/** 节点单击事件 */
const handleNodeClick = (data: Subject) => {
  queryParams.value.subjectId = data.subjectId
  getHasCourse()
}
const getSubjectTree = async () => {
  let { data } = await reqSubjectTree()
  subjectOptions.value = data
}
onMounted(() => {
  // 获取table数据
  getHasCourse()
  getSubjectTree()
  getTeacherList()
})
</script>

<style scoped>
.query_width {
  width: 240px;
}
.date_width {
  width: 308px;
}
</style>
